<template>
  <view class="container">
    <!-- 返回按鈕 -->
    <BackButton />
    
    <div id="video-container"></div>
    <button @click="toggleCamera">切换摄像头</button>
  </view>
</template>

<script>
import BackButton from '@/components/BackButton.vue'

export default {
  data() {
    return {
      videoStream: null,
      videoFacingMode: 'user',
      videoElement: null
    };
  },
  methods: {
    async startCamera() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({
          video: { facingMode: this.videoFacingMode },
          audio: false
        });
        this.videoStream = stream;

        // 如果之前有 video 元素就移除
        const container = document.getElementById('video-container');
        if (this.videoElement) {
          container.removeChild(this.videoElement);
        }

        // 创建原生 video 元素
        const video = document.createElement('video');
        video.autoplay = true;
        video.muted = true;
        video.playsInline = true;
        video.style.width = '100%';
        video.style.maxWidth = '600px';
        video.style.height = '400px';
        video.style.background = 'black';
        video.style.objectFit = 'cover';
        video.style.borderRadius = '10px';
        video.style.marginBottom = '16px';

        // 设置媒体流
        video.srcObject = stream;

        // 添加到容器中
        container.appendChild(video);
        this.videoElement = video;

      } catch (error) {
        console.error('摄像头访问失败:', error);
        uni.showToast({
          title: '摄像头权限被拒绝或设备不支持',
          icon: 'none'
        });
      }
    },
    toggleCamera() {
      this.videoFacingMode = this.videoFacingMode === 'user' ? 'environment' : 'user';
      this.stopCamera();
      this.startCamera();
    },
    stopCamera() {
      if (this.videoStream) {
        this.videoStream.getTracks().forEach(track => track.stop());
        this.videoStream = null;
      }
    }
  },
  mounted() {
    this.startCamera();
  },
  beforeDestroy() {
    this.stopCamera();
  }
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

button {
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
}
</style>